package com.huopaolan.yohuoshop.Mvp.View.Activity;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.huopaolan.lib_core.Base.BaseActivity;
import com.huopaolan.yohuoshop.Bean.BaseEntity;
import com.huopaolan.yohuoshop.Bean.UserMessageEntity;
import com.huopaolan.yohuoshop.Dao.Service.DBService;
import com.huopaolan.yohuoshop.Di.Compont.DaggerUserDetailsCompont;
import com.huopaolan.yohuoshop.Di.Modules.UserDetailsModules;
import com.huopaolan.yohuoshop.Mvp.Contract.UserContract;
import com.huopaolan.yohuoshop.Mvp.Presenter.UserDetailsPresenter;
import com.huopaolan.yohuoshop.NetWork.API;
import com.huopaolan.yohuoshop.R;
import com.huopaolan.yohuoshop.Sp.SpUtils;

import java.io.File;

public class PersonalDetailsActivity extends BaseActivity<UserDetailsPresenter> implements UserContract.UserDetailsIView, View.OnClickListener {
    private ImageView user_out, iv_sel_user_qr_code;
    private SimpleDraweeView user_head;
    private TextView user_name, user_sex, user_data, user_height, user_weight, right_button, cancel_button;
    private DatePicker datePicker;
    private PopupWindow update_birthday;
//    private String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE
//            , Manifest.permission.WRITE_EXTERNAL_STORAGE
//            , Manifest.permission.CAMERA};

    @Override
    public int layoutID() {
        return R.layout.activity_personal_details;
    }

    @Override
    public void initView() {
        user_out = findViewById(R.id.user_out);
        user_out.setOnClickListener(this);
        //初始化控件
        iv_sel_user_qr_code = findViewById(R.id.iv_sel_user_qr_code);
        user_head = findViewById(R.id.iv_sel_user_user_head);
        user_name = findViewById(R.id.tv_sel_user_nick_name);
        user_sex = findViewById(R.id.tv_sel_user_user_sex);
        user_data = findViewById(R.id.tv_sel_user_user_birthday);
        user_height = findViewById(R.id.tv_sel_user_user_height);
        user_weight = findViewById(R.id.tv_sel_user_user_weight);
        iv_sel_user_qr_code.setOnClickListener(this);
        user_head.setOnClickListener(this);
        user_name.setOnClickListener(this);
        user_sex.setOnClickListener(this);
        user_data.setOnClickListener(this);
        user_height.setOnClickListener(this);
        user_weight.setOnClickListener(this);
    }

    @Override
    protected void onStart() {
        Window window = getWindow();
        window.setStatusBarColor(Color.BLACK);
        super.onStart();
    }

    @Override
    protected void onResume() {
        String spReadUser = SpUtils.getInstance().SpReadUser();
        Cursor user = DBService.getDbService().query("User", "user_id=?", new String[]{spReadUser});
        while (user.moveToNext()) {
            String user_names = user.getString(user.getColumnIndex("nick_name"));
            String user_sexs = user.getString(user.getColumnIndex("user_sex"));
            String user_birthday = user.getString(user.getColumnIndex("user_birthday"));
            String user_heights = user.getString(user.getColumnIndex("user_height"));
            String user_weights = user.getString(user.getColumnIndex("user_weight"));
            user_name.setText("" + user_names);
            user_sex.setText("" + user_sexs);
            user_data.setText("" + user_birthday);
            user_height.setText("" + user_heights);
            user_weight.setText("" + user_weights);
        }
        DBService.getDbService().close();
        super.onResume();
    }

    @Override
    public void initData() {
        String spReadUser = SpUtils.getInstance().SpReadUser();
        Cursor user = DBService.getDbService().query("User", "user_id=?", new String[]{spReadUser});
        while (user.moveToNext()) {
            String user_id = user.getString(user.getColumnIndex("user_id"));
            String user_names = user.getString(user.getColumnIndex("nick_name"));
            String user_sexs = user.getString(user.getColumnIndex("user_sex"));
            String user_birthday = user.getString(user.getColumnIndex("user_birthday"));
            String user_heights = user.getString(user.getColumnIndex("user_height"));
            String user_weights = user.getString(user.getColumnIndex("user_weight"));
            p.UpdateUserRequest(user_id, user_names, user_sexs, user_birthday, user_heights, user_weights);
            p.SelUserRequest(user_id);
        }
        DBService.getDbService().close();
    }

    @Override
    public void setUpDagger() {
        DaggerUserDetailsCompont.builder()
                .userDetailsModules(new UserDetailsModules(this))
                .build().inject(this);
    }

    @Override
    public void UserDetailsSuccess(BaseEntity entity) {
        if (entity == null) {
            return;
        }
        Toast.makeText(this, "" + entity.msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void SelUserDetailsSuccess(UserMessageEntity entity) {
        if (entity == null) {
            return;
        }
        user_name.setText("" + entity.values.get(0).nick_name);
        user_sex.setText("" + entity.values.get(0).user_sex);
        user_data.setText("" + entity.values.get(0).user_birthday);
        user_height.setText("" + entity.values.get(0).user_height);
        user_weight.setText("" + entity.values.get(0).user_weight);
        String spReadUser = SpUtils.getInstance().SpReadUser();
        ContentValues values = new ContentValues();
        values.put("user_head", entity.values.get(0).user_head);
        int user = DBService.getDbService().update("User", values, "user_id=?", new String[]{spReadUser});
        if (user > 0) {
            Log.d("UpDate", "UpdateCreate----->Completed");
        }
        Uri uri = Uri.parse(API.BaseUrl + entity.values.get(0).user_head);
        ImagePipeline imagePipeline = Fresco.getImagePipeline();
        imagePipeline.evictFromMemoryCache(uri);
        imagePipeline.evictFromDiskCache(uri);
        imagePipeline.evictFromDiskCache(uri);
        user_head.setImageURI(uri);
//        Glide.with(this).load(API.BaseUrl + entity.values.get(0).user_head)
//                .asBitmap()
//                .skipMemoryCache(true)
//                .diskCacheStrategy(DiskCacheStrategy.NONE)
//                .into(user_head);
        DBService.getDbService().close();
    }

    @Override
    public void UploadUserSuccess(BaseEntity entity) {
        if (entity == null) {
            return;
        }
        Toast.makeText(this, "" + entity.msg, Toast.LENGTH_SHORT).show();
        p.destroy();
    }

    @Override
    public void showDialog() {

    }

    @Override
    public void hideDialog() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_out:
                finish();
                break;
            case R.id.tv_sel_user_nick_name:
                startActivity(new Intent(this, UserNameUpdateActivity.class));
                break;
            case R.id.tv_sel_user_user_sex:
                final PopupWindow update_sex = new PopupWindow(this);
                View view_sex = LayoutInflater.from(this).inflate(R.layout.item_sel_sex_layout, null);
                final Button sex_boy = view_sex.findViewById(R.id.sel_sex_boy);
                final Button sex_girl = view_sex.findViewById(R.id.sel_sex_girl);
                Button sex_cancel = view_sex.findViewById(R.id.sel_sex_cancel);
                sex_boy.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String spReadUser = SpUtils.getInstance().SpReadUser();
                        String boy = sex_boy.getText().toString();
                        ContentValues values = new ContentValues();
                        values.put("user_sex", boy);
                        int user = DBService.getDbService().update("User", values, "user_id=?", new String[]{spReadUser});
                        user_sex.setText("" + boy);
                        Toast.makeText(PersonalDetailsActivity.this, "" + user, Toast.LENGTH_SHORT).show();
                        if (user > 0) {
                            update_sex.dismiss();
                            Toast.makeText(PersonalDetailsActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                sex_girl.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String spReadUser = SpUtils.getInstance().SpReadUser();
                        String girl = sex_girl.getText().toString();
                        ContentValues values = new ContentValues();
                        values.put("user_sex", girl);
                        int user = DBService.getDbService().update("User", values, "user_id=?", new String[]{spReadUser});
                        user_sex.setText("" + girl);
                        Toast.makeText(PersonalDetailsActivity.this, "" + user, Toast.LENGTH_SHORT).show();
                        if (user > 0) {
                            update_sex.dismiss();
                            Toast.makeText(PersonalDetailsActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                sex_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        update_sex.dismiss();
                    }
                });
                update_sex.setContentView(view_sex);
                update_sex.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
                update_sex.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
                update_sex.setOutsideTouchable(true);
                update_sex.showAtLocation(view_sex, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.tv_sel_user_user_birthday:
                update_birthday = new PopupWindow(this);
                View inflate = LayoutInflater.from(this).inflate(R.layout.item_bottom_date, null);
                right_button = inflate.findViewById(R.id.tv_item_bottom_date_sure);
                cancel_button = inflate.findViewById(R.id.tv_item_bottom_date_qx);
                right_button.setOnClickListener(this);
                cancel_button.setOnClickListener(this);
                datePicker = inflate.findViewById(R.id.dp_item_bottom_date);
                right_button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int dayOfMonth = datePicker.getDayOfMonth();
                        int month = datePicker.getMonth();
                        int year = datePicker.getYear();
                        String spReadUser = SpUtils.getInstance().SpReadUser();
                        String dateAll = year + "-" + (month + 1) + "-" + dayOfMonth;
                        ContentValues values = new ContentValues();
                        values.put("user_birthday", dateAll);
                        int user = DBService.getDbService().update("User", values, "user_id=?", new String[]{spReadUser});
                        user_data.setText("" + dateAll);
                        Toast.makeText(PersonalDetailsActivity.this, "" + user, Toast.LENGTH_SHORT).show();
                        if (user > 0) {
                            update_birthday.dismiss();
                            Toast.makeText(PersonalDetailsActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                cancel_button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        update_birthday.dismiss();
                    }
                });
                update_birthday.setOutsideTouchable(true);
                update_birthday.setContentView(inflate);
                update_birthday.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
                update_birthday.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
                update_birthday.showAtLocation(inflate, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.tv_sel_user_user_height:
                startActivity(new Intent(this, HeightAndWeightActivity.class));
                break;
            case R.id.tv_sel_user_user_weight:
                startActivity(new Intent(this, HeightAndWeightActivity.class));
                break;
            case R.id.iv_sel_user_user_head:
                final PopupWindow update_head = new PopupWindow(this);
                View view_head = LayoutInflater.from(this).inflate(R.layout.item_photo_layout, null);
                final Button photo_take = view_head.findViewById(R.id.sel_photo_take);
                final Button photo_this = view_head.findViewById(R.id.sel_photo_this);
                Button sel_cancel = view_head.findViewById(R.id.sel_cancel);
                photo_take.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
                photo_this.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startPhoto();
                    }
                });
                sel_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        update_head.dismiss();
                    }
                });
                update_head.setContentView(view_head);
                update_head.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
                update_head.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
                update_head.setOutsideTouchable(true);
                update_head.showAtLocation(view_head, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.iv_sel_user_qr_code:
                startActivity(new Intent(this, QrCodeActivity.class));
                break;
        }
    }

    //打开图库
    private void startPhoto() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, 101);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == Activity.RESULT_OK) {
            Toast.makeText(this, "打开图库成功", Toast.LENGTH_SHORT).show();
            Uri uri = data.getData();
            user_head.setImageURI(uri);
            Log.d("HeadImage", "" + uri.getPath());
            //上传头像 sp获取id
            String spReadUser = SpUtils.getInstance().SpReadUser();
            Cursor user = DBService.getDbService().query("User", "user_id=?", new String[]{spReadUser});
            while (user.moveToNext()) {
                String user_id = user.getString(user.getColumnIndex("user_id"));
                p.uploadRequest(getImage(data), user_id);
            }
            DBService.getDbService().close();
        }
    }

    /**
     * 封装Uri 和 查询属性
     *
     * @param data 根据Intent获取Uri
     */
    private File getImage(Intent data) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Uri uri = data.getData();
        return getContentProvider(uri, projection);
    }

    /**
     * 从内容提供者获取图片绝对路径
     * 返回File文件
     */
    public File getContentProvider(Uri uri, String[] projection) {
        Cursor cursor = getContentResolver().query(uri, projection, null,
                null, null);
        if (null == cursor) {
            return null;
        } else if (cursor.moveToNext()) {
            return new File(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)));
        } else {
            return null;
        }
    }
}
